<?php
// 保存设置的PHP文件

// 在引入config.php之前不输出任何内容
require_once 'config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 记录请求数据用于调试
        $rawInput = file_get_contents('php://input');
        
        // 检查是否有数据
        if (empty($rawInput)) {
            throw new Exception('没有接收到数据');
        }
        
        $input = json_decode($rawInput, true);
        
        // 检查JSON解析是否成功
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('JSON解析错误: ' . json_last_error_msg());
        }
        
        if (!$input) {
            throw new Exception('无效的JSON数据');
        }
        
        // 检查必需的字段
        if (!isset($input['baiduOcr'])) {
            throw new Exception('缺少baiduOcr字段');
        }
        
        if (!isset($input['ocrEngine'])) {
            throw new Exception('缺少ocrEngine字段');
        }
        
        // 保存配置
        $newConfig = [
            'baiduOcr' => [
                'apiKey' => $input['baiduOcr']['apiKey'] ?? '',
                'secretKey' => $input['baiduOcr']['secretKey'] ?? ''
            ],
            'ocrEngine' => $input['ocrEngine'] ?? 'tesseract'
        ];
        
        $savedConfig = saveConfig($newConfig);
        
        // 返回成功响应
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => '设置已保存',
            'config' => $savedConfig
        ]);
    } else {
        throw new Exception('只支持POST请求');
    }
} catch (Exception $e) {
    // 返回错误响应
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>